import logging
from logging import handlers
import appium.webdriver
from appium import webdriver
import os
import json
from selenium import webdriver

from config import DIR_PATH, HOST


class GetDriver:
    __app_driver = None
    __web_driver = None

    # 获取appdriver
    @classmethod
    def get_app_driver(cls):
        if cls.__app_driver is None:
            desired_caps = {}
            # 安卓系统
            desired_caps["platformName"] = "Android"
            # 系统的版本号
            desired_caps["platformVersion"] = "7.1"
            # 当前要测试的设备的名称，通过adb devices命令获取
            desired_caps["deviceName"] = "127.0.0.1:62001"
            # 要启动的app的名称（包名），在手机中，包名是app的唯一标识
            desired_caps["appPackage"] = "com.tpshop.malls"
            # 要启动的app的哪个界面
            desired_caps["appActivity"] = ".SPMainActivity"
            # 设置中文
            desired_caps["unicodeKeyboard"] = True
            desired_caps["resetKeyboard"] = True
            desired_caps["automationName"] = "Uiautomator2"

            # 启动app，从appium库里面导入drive对象
            cls.__app_driver = appium.webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
            cls.__app_driver.implicitly_wait(10)
        return cls.__app_driver

    @classmethod
    def get_web_driver(cls):
        if cls.__web_driver is None:
            cls.driver = webdriver.Chrome()
            cls.driver.get(HOST)
            cls.driver.maximize_window()
        return cls.driver


def read_json(filename, key):
    file_path = DIR_PATH + os.sep + "data" + os.sep + filename
    with open(file_path, "r", encoding="utf-8") as f:
        json_data = json.load(f)
        list_data = []
        for i in json_data.get(key):
            tmp = tuple(i.values())[1:]
            list_data.append(tmp)
        return list_data


# 日志
class GetLog:
    __log = None

    @classmethod
    def get_log(cls):
        if cls.__log is None:
            # 获取日志器
            cls.__log = logging.getLogger()
            # 设置日志打印级别
            cls.__log.setLevel(logging.INFO)
            # 获取处理器
            # 输出到控制台的处理器对象
            st = logging.StreamHandler()
            # 输出到日志文件的处理器对象
            filename = DIR_PATH + os.sep + "log" + os.sep + "tpshop.log"
            fh = logging.handlers.TimedRotatingFileHandler(filename, when="midnight", interval=1,
                                                           backupCount=3, encoding="utf_8")
            # 获取格式器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            formatter = logging.Formatter(fmt)
            # 将格式器添加到处理器
            fh.setFormatter(formatter)
            st.setFormatter(formatter)
            # 将控制台处理器添加到日志器
            cls.__log.addHandler(st)
            # 将日志文件处理器添加到日志器
            cls.__log.addHandler(fh)
            # 返回日志器
        return cls.__log



if __name__ == '__main__':
    # print(read_json("login_order.json", "order"))
    GetLog.get_log().info("日志测试")